/**
 * 从 file 域获取 本地图片 url
 */
function getFileUrl(sourceId) {
    var url;
    if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
        url = document.getElementById(sourceId).value;
    } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    }
    return url;
}

/**
 * 将本地图片 显示到浏览器上
 */
function preImg(sourceId, targetId) {
    var url = getFileUrl(sourceId);
    var imgPre = document.getElementById(targetId);
    imgPre.src = url;
}

$(function() {

	$("#backButton").click(function() {
		/*history.back(-1);*/
		getParkInfoList();
	});

	$("#parkEdit_rejectForm").validate({
        focusCleanup: true,
        focusInvalid: false,
        onkeyup: true,
        rules: {
            parkName: {
                required: true
            },
            freeParkingTime: {
                number:true
            },
            dayQuotaAmount: {
                number:true
            },
            feeAmount: {
                number:true
            }
        },
        messages: {
            parkName: {
                required: "停车场名称不能为空"
            },
            freeParkingTime: {
                number: "只能输入数字"
            },
            dayQuotaAmount: {
                number: "请输入有效金额"
            },
            feeAmount: {
                number: "请输入有效金额"
            }
        },
        submitHandler: submit
    });

    //按时段添加行
    $("#addByTimeRowBtn").click(function(){
        var rowNum = $("div.byTimeRow").length;
        if(rowNum >= 15){
            alert("最多只能添加15个");
            return;
        }
        var rowHtml ='<div class="byTimeRow" id="byTimeRow' + rowNum +'">'+
            '<label class="control-label fm5">每</label>'+
            '<input class="form-control fmw" name="feeInterval" type="text" />'+
            '<label class="control-label fm3">分钟</label>'+
            '<label class="control-label fm5">收费</label>'+
            '<input class="form-control fmw" name="amount" type="text" />'+
            '<label class="control-label fm3">元</label>'+
            '<label class="control-label fm5">时间范围</label>'+
            '<input class="form-control fw8" name="startTime" type="time" />'+
            '<label class="control-label mm">-</label>'+
            '<input class="form-control fw8" name="endTime" type="time" />'+
            '<label class="fa fa-times mc byTimeRowDelete"></label>'+
            '</div>';
        $("#byTimeDiv").append(rowHtml);
        $(".byTimeRowDelete").bind("click",function () {
            $(this).parent().remove();
        })
    });

    initBaseDataSelect("Property", "#property", "产权方");							//产权方
    initBaseDataSelect("ParkType", "#parkType", "业态");							//业态
    initBaseDataSelect("BusinessEntity", "#businessEntity", "经营主体");			//经营主体
    initBaseDataSelect("IntegralBodyType", "#integralBodyType", "积分主体类型");	//积分主体类型

	//是否收费下拉框
    $("#isFee").find("option[value='"+ $("#isFee").attr('value') + "']").attr("selected",true);

    initByTimeData();

    initProvinceSelect();   //所在省份
    //级联所在城市
    $("#provinceCode").change(function(){
        if($(this).val()!="")
            $("#provinceName").val($(this).find("option:selected").text());

        var value = $("#cityCode").attr("value");
        $.getJSON(ctx + "/mgr/regionCode/listByLevelCode/" + $(this).val(), {random: Math.random}, function(json){
            var options = "<option value=''>请选择所在城市</option>";
            $.each(json,function(index, row) {
                options += "<option "+ (row.levelCode==value?"selected='selected'":"") +" value='" + row.levelCode + "'>" + row.regionName + "</option>";
            });
            $("#cityCode").html(options);
        });
    });
    //级联所在城市
    $("#cityCode").change(function(){
        if($(this).val()!="")
            $("#cityName").val($(this).find("option:selected").text());
    });

});


/**
 * 初始化省份下拉菜单
 * @param type
 * @param jqueryId
 */
function initProvinceSelect() {
    var value = $("#provinceCode").attr("value");
    $.getJSON(ctx + "/mgr/regionCode/getProvinces", {random: Math.random}, function(json){
        var options = "<option value=''>请选择所在省份</option>";
        $.each(json,function(index, row) {
            options += "<option "+ (row.levelCode==value?"selected='selected'":"") +" value='" + row.levelCode + "'>" + row.regionName + "</option>";
        });
        $("#provinceCode").html(options);
        $("#provinceCode").change();
    });
}

function initByTimeData(){
    for(var i= 0;i < rules.length;i++){
        var startTime = (rules[i].startTime!=null?rules[i].startTime.substr(0, 2) + ":" + rules[i].startTime.substr(2, 4):"");
        var endTime = (rules[i].endTime!=null?rules[i].endTime.substr(0, 2) + ":" + rules[i].endTime.substr(2, 4):"");

        var rowHtml ='<div class="byTimeRow" id="byTimeRow' + i +'">'+
            '<label class="control-label fm5">每</label>'+
            '<input class="form-control fmw" name="feeInterval" type="text" value="'+rules[i].feeInterval+'" />'+
            '<label class="control-label fm3">分钟</label>'+
            '<label class="control-label fm5">收费</label>'+
            '<input class="form-control fmw" name="amount" type="text" value="'+rules[i].amount+'" />'+
            '<label class="control-label fm3">元</label>'+
            '<label class="control-label fm5">时间范围</label>'+
            '<input class="form-control fw8" name="startTime" type="time" value="'+startTime+'" />'+
            '<label class="control-label mm">-</label>'+
            '<input class="form-control fw8" name="endTime" type="time" value="'+endTime+'" />'+
            '<label class="fa fa-times mc byTimeRowDelete"></label>'+
            '</div>';
        $("#byTimeDiv").append(rowHtml);
        $(".byTimeRowDelete").bind("click",function () {
            $(this).parent().remove();
        })
    };
}


/**
 * 初始化数据字典下拉菜单
 * @param type
 * @param jqueryId
 */
function initBaseDataSelect(type, jqueryId, name) {
   var value = $(jqueryId).attr("value");
    //积分主体类型
    $.getJSON(ctx + "/mgr/basedata/listByType/" + type, {random: Math.random}, function(json){
        var options = "<option value=''>请选择" + name + "</option>";
        $.each(json,function(index, row) {
        	console.info(row.value, value);
            options += "<option "+ (row.value==value?"selected='selected'":"") +" value='" + row.value + "'>" + row.text + "</option>";
        });
        $(jqueryId).html(options);
    });
}

/**
 * 处理按时间行数据
 */
function byTimeData(){
    var reg = new RegExp("^\\d+$");
    var array = new Array();
    //遍历按时段数据行
    var flag = true;
    $(".byTimeRow").each(function(index,element){
        var feeIntervalValue = $(this).find("input[name='feeInterval']").val();
        var amountValue = $(this).find("input[name='amount']").val();
        var startTimeValue = $(this).find("input[name='startTime']").val().replace(":","");
        var endTimeValue = $(this).find("input[name='endTime']").val().replace(":","");
        if(!reg.test(feeIntervalValue) || !reg.test(amountValue)) {
            flag = false;
            alert("按时段'分钟数'和'收费'必须是正整数");
            return false;
        }
        array.push({
            feeInterval: feeIntervalValue,
            amount: amountValue,
            startTime: startTimeValue,
            endTime: endTimeValue
        });
    });
    $("#rules").val(JSON.stringify(array));
    return flag;
}

/**
 * 编辑停车场信息
 */
function submit() {
    if(!byTimeData()){
        return;
    };

    //提交数据
    var formData = new FormData($("#parkEdit_rejectForm")[0]);
    console.info(formData);
    $.ajax({
        url: ctx + "/mgr/park/edit",
        type: 'post',
        contentType: false,
        processData: false,
        data: formData,
        dataType: 'json',
        timeout: ajaxTimeout,
        error: function (json) {
            toastr.error("修改停车场失败，网络连接超时请重新登陆")
        },
        success: function (json) {
            if (json.isSuccess==0) {
                toastr.success("修改成功");
            } else {
                toastr.error("修改失败");
            }
        }
    });
}

/**
 * 查看停车场信息列表
 * @param userId 用户ID
 */
function getParkInfoList() {
	var url = ctx + "/mgr/park/list";
	window.location.href = url;
}